/*
    英译汉服务器demo
*/

#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <string>
#include <unordered_map>

class DictServer
{
public:
    DictServer(uint16_t port)
    :_server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port), "DictServer", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&DictServer::OnConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DictServer::OnMessage, this,
            std::placeholders::_1,
            std::placeholders::_2,
            std::placeholders::_3));
    }
    void start()
    {
        _server.start();
        _baseloop.loop();
    }
private:
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected() == true)
        {
            std::cout << "连接建立" << std::endl;
        }
        else
        {
            std::cout << "连接关闭" << std::endl;
        }
    }

    void OnMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        static std::unordered_map<std::string, std::string> dict_map = { 
            {"hello", "你好"},
            {"world", "世界"},
            {"bite", "比特"}
        };
        std::string msg = buf->retrieveAllAsString();
        std::string res;
        if (dict_map.find(msg) != dict_map.end())
        {
            res = dict_map[msg];
        }
        else
        {
            res = "未知单词";
        }
        conn->send(res);
    }

private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    DictServer dict(9090);
    dict.start();
    return 0;
}